const Router = require('koa-router');
const router = new Router();
const {db, QueryTypes, Op, DataTypes} = require('../models/db')
const {treeTableSave} = require('../tools/treeTableSave')
const fs = require("fs");
const tools = require("../tools/tool");
const xlsx = require("node-xlsx");
const {now} = require("lodash");
const downurl = 'http://192.168.3.3:9998/'
const cnchar = require('cnchar')

router.post('/design/save', async ctx => {
    try {
        let formData = ctx.request.body.formData;
        let mod = ctx.request.body.mod;
        let isTree = ctx.request.body?.isTree
        if(!mod) return ctx.err('未知模型名称')
        if (!formData.id) {
            formData.ct = new Date()
        }
        if(mod) {
            let attrs = db.models[mod].getAttributes()
            // 如果有拼音字段，自动转换拼音首字母
            for (let i in attrs) {
                if(i === 'py') {
                    formData.py = cnchar.spell(formData.name, 'first', 'low')
                }
            }
            if(isTree) {
                // 树形表的 新增 更新
                let ret = await treeTableSave(mod, ctx)
                if (ret) return  ctx.suc('保存成功', ret)
                return ctx.err('保存失败')
            }
            else {
                if (formData.id) {
                    // 修改保存
                    await db.models[mod].update(formData, {
                        where: {id: formData.id}
                    })
                    ctx.suc('保存成功', formData.id)
                }
                else {
                    if(db.models[mod].getAttributes().tenantid) {
                        formData.tenantid = ctx.user.tenantid
                    }
                    // 新增
                    let ret = await db.models[mod].create(formData)
                    ctx.suc('保存成功', ret)
                }
            }
        }
        else {
            return ctx.err('未知模型')
        }
    }
    catch (error) {
        ctx.err(error)
    }
})
// 表单设计保存
router.post('/design/saveForm', async ctx => {
    let formData = ctx.request.body.formData;
    let id = formData.id;
    if(!id) return ctx.err('未保存')
    let mod = 'design'
    let model = await db.models[mod].findOne({
        where: {
            id: id
        }
    })
    if(!model) return  ctx.err('查询失败')
    model.params = JSON.stringify(formData.params)
    await model.save()
    let par = formData.params;
    let fieldStr = ''
    let idstr = ``
    let tenantStr = ``
    let cby = ''
    let uby = ''
    let dby = ''
    let ctime = ''
    let utime = ''
    let dtime = ''
    let isDel = ''
    if(formData.params.showId) {
        idstr = `id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true,comment:\'表自增ID\'},`
    }
    if(formData.params.tenantId) {
        tenantStr = `tenantId: {type:DataTypes.INTEGER,allowNull:false,comment:'租户',  },`
    }
    if(formData.params.cby) {
        cby = 'cby: {type: DataTypes.INTEGER,comment:\'创建人\'},'
    }
    if(formData.params.uby) {
        uby = 'uby: {type: DataTypes.INTEGER,comment:\'更新人\'},'
    }
    if(formData.params.dby) {
        dby = 'dby: {type: DataTypes.INTEGER,comment:\'删除人\'},'
    }
    if(formData.params.ctime) {
        ctime = 'ctime: {type: DataTypes.STRING,comment:\'创建时间\'},'
    }
    if(formData.params.utime) {
        utime = 'utime: {type: DataTypes.STRING,comment:\'更新时间\'},'
    }
    if(formData.params.dtime) {
        dtime = 'dtime: {type: DataTypes.STRING,comment:\'删除时间\', },'
    }
    if(formData.params.softDel) {
        isDel = 'isDel: {type: DataTypes.INTEGER,comment:\'删除0|1\', },'
    }
    par.fields.map(row => {
        if(row.field && row.fieldType) {
            let dt = ''
            if(row.fieldType === 'text' || row.fieldType === 'date' || row.fieldType === 'datetime') {
                dt = 'STRING'
            }
            if(row.fieldType === 'int' || row.fieldType === 'boolean' || row.fieldType === 'number') {
                dt = 'INTEGER'
            }
            if(row.fieldType === 'decimal') {
                dt = 'DECIMAL(18,2)'
            }
            if(row.fieldType === 'virtual') {
                dt = 'VIRTUAL'
            }
            if(dt) {
                let str = `${row.field}:{type: DataTypes.${dt},comment:'${row.title}'}, \n`
                fieldStr = fieldStr + str
            }
        }
    })
    let tb = `const {DataTypes, db } = require("../db");
db.define('${par.mod}', {
${idstr}
${tenantStr}
${fieldStr}
${isDel}
${cby}
${uby}
${dby}
${ctime}
${utime}
${dtime}
}, {
    tableName: '${par.tableName}',
    timestamps: false
});`
    if(par.mod)
        saveFile(par.mod, tb)
    return ctx.suc('已保存')
})
router.post('/design/del', async ctx => {
    try {
        let ids = ctx.request.body.ids;
        let mod = ctx.request.body.mod;
        let isTree = ctx.request.body?.isTree;
        if (isTree) {
            // 找出code 摸查子分类 并删除
            for(let id in ids) {
                let codeModel = await db.models[mod].findOne({
                    where: {
                        id: ids[id]
                    }
                })
                if(codeModel) {
                    await db.models[mod].destroy({
                        where: {
                            code: {
                                [Op.like]: codeModel.code +'%'
                            }
                        }
                    })
                }
            }
            ctx.suc('已删除 ' + ids.length + ' 条记录')
        }
        else {
            await db.models[mod].destroy({
                where: {
                    id: {
                        [Op.in]: ids
                    }
                }
            })
            ctx.suc('已删除 ' + ids.length + ' 条记录')
        }
    }
    catch (error) {
        ctx.err(error)
    }
})
// 直接通过sql语句查询
router.post('/design/sqlList', async ctx => {
    try {
        let sql = ctx.request.body.sql;
        if(sql) {
            let ret = await db.query(sql, {type: QueryTypes.SELECT});
            return ctx.suc('', ret)
        }
        ctx.suc('', [])
    }
    catch (error) {
        ctx.err(error)
    }
})
// 直接通过sql语句查询
router.post('/design/fileImport', async ctx => {
    try {
        const {file} = ctx.request.files
        if(file) {
            return ctx.suc(`${file.name}`)
        }
        else {
            return  ctx.err('读取文件失败')
        }
        return  ctx.suc('suc')
    } catch (e) {
        return ctx.err('err')
    }
})
router.post('/design/syncTable', async ctx => {
    // try {
    //     let id = ctx.request.body.id;
    //     if(!id) return ctx.err('未找到模型');
    //     let model = await db.models['models'].findOne({ where: {id: id} });
    //     if(!model) return ctx.err('未找到模型');
    //     // 查询数据库中是否有表
    //     let totalModel = await db.query(`SELECT count(*) total from pg_tables where tablename='${model.tablename}'`, {type: QueryTypes.SELECT, plain: true});
    //     if (parseInt(totalModel.total) !== 0 ) {
    //         let hasData = await db.models[model.tablename].count();
    //         if (hasData > 0) return ctx.err('已有数据，请手动更新数据库表');
    //     }
    //     await db.models[model.tablename].sync({force: true});
    //     ctx.suc('同步成功');
    // }
    // catch (error) {
    //     ctx.err(error)
    // }
})
router.post('/design/syncTableFile', async ctx => {
    try {
        let id = ctx.request.body.id;
        if(!id) return ctx.err('未找到模型');
        let model = await db.models['models'].findOne({where: {id: id}});
        if(!model) return ctx.err('未找到模型');
        let data = await combFile(model)
        saveFile(model.tablename, data)
        ctx.suc('')
    }
    catch (error) {
        ctx.err(error)
    }
})
router.post('/design/list', async ctx => {
    try {
        let ret = await page(ctx)
        if(ret) {
            return ctx.suc('', ret)
        }
        return ctx.err('查询失败')
    }
    catch (error) {
        ctx.err(error)
    }
})
router.post('/design/exportFile', async ctx => {
    try {
        const list = [
            {
                name: '下载文件',
                data: [
                    ['名称一', '名称二', '名称三', 'ss'],
                    ['1', '2', '3'],
                    [null, '2', '3'],
                ]
            }
        ]
        return ctx.suc('suc')
    } catch (e) {
        console.log(e)
    }
})
router.post('/design/modToTable', async ctx => {
    try {
        let mod = ctx.request.body.mod
        await db.models[mod].sync({force: true, logging: console.log})
        return ctx.suc('已保存')
    } catch (e) {
        console.log(e)
        ctx.err(e)
    }

})

router.post('/design/tableToMod', async ctx => {
    let tableName = ctx.request.body.tableName
    if(tableName) {
        let sql = `
        SELECT 
            表名       = d.name,
            表说明     = isnull(f.value,''),
            字段序号   = a.colorder,
            字段名     = a.name,
            标识       = case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then 1 else 0 end,
            主键       = case when exists(SELECT 1 FROM sysobjects where xtype='PK' and parent_obj=a.id and name in (
                             SELECT name FROM sysindexes WHERE indid in( SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid))) then 1 else 0 end,
            类型       = b.name,
            占用字节数 = a.length,
            长度       = COLUMNPROPERTY(a.id,a.name,'PRECISION'),
            小数位数   = isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0),
            允许空     = case when a.isnullable=1 then 1 else 0 end,
            默认值     = isnull(e.text,''),
            字段说明   = isnull(g.[value],'')
        FROM 
            syscolumns a
        left join 
            systypes b 
        on 
            a.xusertype=b.xusertype
        inner join 
            sysobjects d 
        on 
            a.id=d.id  and d.xtype='U' and  d.name<>'dtproperties'
        left join 
            syscomments e 
        on 
            a.cdefault=e.id
        left join 
        sys.extended_properties   g 
        on 
            a.id=G.major_id and a.colid=g.minor_id  
        left join
        sys.extended_properties f
        on 
            d.id=f.major_id and f.minor_id=0
        where 
            d.name='${tableName}' 
        order by 
            a.id,a.colorder
        `
        let list = await db.query(sql, {type: QueryTypes.SELECT})
        let ret = saveMod(list, ctx)
        return ret
    }
})
// 组装页面参数
router.post('/design/getParams', async ctx => {
    try {
        let body = ctx.request.body;
        let whichModel = body.whichModel;
        if(whichModel) {

        }

        ctx.suc('保存成功 ')
    }
    catch (error) {
        ctx.err(error)
    }
})
// 功能模板
router.post('/design/getBtnTemp', async ctx => {
    let ret = [
        {
            name: '工具栏',
            tpl: tools.obj2str(getBtn())
        },
        {
            name: '按钮点击',
            tpl: tools.obj2str(btnClick())
        },
        {
            name: '手机搜索',
            tpl: tools.obj2str(openMobileSearch())
        },
        {
            name: '行按钮',
            tpl: tools.obj2str(rowBtn())
        },
        {
            name: '行按钮点击',
            tpl: tools.obj2str(rowBtnClick())
        },
    ]

    return ctx.suc('', tools.obj2str(ret))
})
// 生成导入模板
router.post('/design/moban', async ctx => {
    try {
        const list = [
            {
                name: '下载文件',
                data: [
                    ['名称一', '名称二', '名称三', 'ss'],
                    ['1', '2', '3'],
                    [null, '2', '3'],
                ]
            }
        ]
        const mobanData = ctx.request.body.formData;
        let obj = {
            name: mobanData.title,
            data: []
        }
        let oneRow = []
        mobanData.columns.map(row => {
            if(row.excelin) {
                oneRow.push(row.title)
            }
        })
        obj.data.push(oneRow)
        if(obj.data.length > 0) {
            const fname = await exportOut(obj.name, [obj])
            return ctx.suc('正在导出', downurl + fname)
        }
        else {
            return ctx.err('无导出数据')
        }
    } catch (e) {
        console.log(e)
    }
})
router.post('/design/toPy', async ctx => {
    let mods = ['contact', 'goods']
    let tenantId=16
    for(let i =0;i<mods.length;i++) { 
        let mod = mods[i]
        let list = await db.models[mod].findAll({
            where: {
                tenantId: tenantId
            },
            attributes: ['id', 'name']
        })
        for (let i = 0; i < list.length; i++) {
            let name = list[i].name.replace('（','')
            name = name.replace('）','')
            name = name.replace(')','')
            name = name.replace('(','')
            name = name.replace('-','')
            name = name.replace('*','')
            await db.models[mod].update({pinYin: tools.py(name)},
                {
                    where: {
                        id: list[i].id
                    }
                })
        }
    }
    return ctx.suc('成功')
})
//
router.post('/design/test', async ctx => {
    let arr = [
        {name: '1'},
        {name: '2'},
    ]
    let ret =  await db.models['tests'].bulkCreate(arr,{returning: false})
    ctx.suc('', ret)
})
router.post('/design/uppostdata', async ctx => {
    let a = await db.query(`select top 5000* from invoice where billType in('SR') and (postData='' or postData is null) `, {type: QueryTypes.SELECT})
    for (let i = 0; i < a.length; i++) {
        let invoice = await db.query(`select * from invoice_other where iid=${a[i].id}`,{type: QueryTypes.SELECT})
        //let invoice = await db.query(`select * from invoice_info where iid=${a[i].id}`,{type: QueryTypes.SELECT})
        let post = a[i]
        post.infos = invoice
        await db.models['invoice'].update({postData: JSON.stringify(post)}, {
            where: {
                id: a[i].id
            }
        })
    }
    return ctx.suc('suc')
})













const setDefault = (data, mod) => {
    let attrs = db.models[mod].getAttributes()
    for(let i in attrs) {
        if(typeof data[i] !== 'undefined') {
            let dataType = attrs[i].type.getDataTypeId()
            if(dataType === 'INTEGER') {
                if(!data[i]) data[i] = null
            }
            if(dataType === 'DECIMAL') {
                if(!data[i]) data[i] = null
            }
            if(dataType === 'STRING') {
                if(!data[i]) data[i] = ''
            }
        }
    }
}

const saveMod = (list, ctx) => {
    let tableName = ctx.request.body.tableName
    let modName = tools.xe.camelCase(list[0].表名.replace(/_/g, '-'))
    let modComent = list[0].表说明
    try {
        let fieldStr = ''
        let idstr = ``
        let transC = 0
        list.map(row => {
            if(row.字段名 === 'id') {
                transC++
                idstr = `id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true,comment:\'表自增ID\'},`
            } else {
                let an = ''
                let defaultValue = ''
                let dt = ''
                if(row.允许空 === 0) {
                    an = 'allowNull:false,'
                }
                if(row.类型 === 'varchar') {
                    if(row.长度 == -1) {
                        dt = `TEXT`
                    }
                    else {
                        dt = `STRING(${row.长度})`
                    }
                    transC++
                }
                if(row.类型 === 'nvarchar') {
                    if(row.长度 == -1) {
                        dt = `TEXT`
                    }
                    else {
                        dt = `STRING(${row.长度})`
                    }
                    transC++
                }
                if(row.类型 === 'text') {
                    dt = 'TEXT'
                    transC++
                }
                if(row.类型 === 'int') {
                    dt = 'INTEGER'
                    transC++
                }
                if(row.类型 === 'float') {
                    dt = 'FLOAT'
                    transC++
                }
                if(row.类型 === 'tinyint') {
                    dt = 'TINYINT'
                    transC++
                }
                if(row.类型 === 'smallint') {
                    dt = 'SMALLINT'
                    transC++
                }
                if(row.类型 === 'decimal') {
                    dt = `DECIMAL(${row.长度}, ${row.小数位数})`
                    transC++
                }
                if(row.类型 === 'datetime') {
                    dt = `DATE`
                    transC++
                }

                if(row.默认值) {
                    defaultValue = 'defaultValue:' + row.默认值.replace('((','').replace('))','')+','
                }
                if(dt) {
                    let str = `${row.字段名}:{type: DataTypes.${dt},${an}${defaultValue}comment:'${row.字段说明}'}, \n`
                    fieldStr = fieldStr + str
                }
            }
        })
        if(transC != list.length) {
            return ctx.err('要转列数量不正确')
        }

        let tb = `// ${modComent}
const {DataTypes, db } = require("../db");
db.define('${modName}', {
${idstr}
${fieldStr}
}, {
    tableName: '${tableName}',
    timestamps: false,
    comment: '${modComent}'
});`
        saveFile(modName, tb)
        return ctx.err('转换成功')
    }
    catch (e) {
        console.log('模型文件保存失败')
        return ctx.err('转换失败')
    }
}
const saveModelField = (par, model) => {
    try {
        let fieldStr = ''
        let idstr = ``
        let tenantStr = ``
        let cby = ''
        let uby = ''
        let dby = ''
        let ctime = ''
        let utime = ''
        let dtime = ''
        let isDel = ''
        let quick = ''
        if(par.showId) {
            idstr = `id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true,comment:\'表自增ID\'},`
        }
        if(par.tenantId) {
            tenantStr = `tenantId: {type:DataTypes.INTEGER,allowNull:false,comment:'租户',  },`
        }
        if(par.cby) {
            cby = 'cby: {type: DataTypes.INTEGER,comment:\'创建人\'},'
        }
        if(par.uby) {
            uby = 'uby: {type: DataTypes.INTEGER,comment:\'更新人\'},'
        }
        if(par.dby) {
            dby = 'dby: {type: DataTypes.INTEGER,comment:\'删除人\'},'
        }
        if(par.ctime) {
            ctime = 'ctime: {type: DataTypes.STRING,comment:\'创建时间\'},'
        }
        if(par.utime) {
            utime = 'utime: {type: DataTypes.STRING,comment:\'更新时间\'},'
        }
        if(par.dtime) {
            dtime = 'dtime: {type: DataTypes.STRING,comment:\'删除时间\', },'
        }
        if(par.softDel) {
            isDel = 'isDel: {type: DataTypes.INTEGER,comment:\'删除0|1\', },'
        }
        if(par.quick) {
            quick = 'quick: {type: DataTypes.STRING,comment:\'快速搜索列\', },'
        }
        if(par.fields && par.fields.length > 0) {
            par.fields.map(row => {
                if(row.field && row.fieldType) {
                    let an = ''
                    let defaultValue = ''
                    if(row.required) {
                        an = 'allowNull:false,'
                    }
                    if(row.default) {
                        defaultValue = `defaultValue:'${row.default}',`
                    }
                    if(row.idField) {
                        let str1 = `${row.idField}:{type: DataTypes.INTEGER,${an}${defaultValue}comment:'${row.title}-ID'}, \n`
                        fieldStr = fieldStr + str1
                        let str = `${row.field}:{type: DataTypes.VIRTUAL,${an}${defaultValue}comment:'${row.title}'}, \n`
                        fieldStr = fieldStr + str
                    }
                    else {
                        let dt = ''
                        if(row.fieldType === 'text' || row.fieldType === 'date' || row.fieldType === 'datetime') {
                            dt = 'STRING'
                        }
                        if(row.fieldType === 'int' || row.fieldType === 'boolean' || row.fieldType === 'number') {
                            dt = 'INTEGER'
                        }
                        if(row.fieldType === 'decimal') {
                            dt = 'DECIMAL(18,2)'
                        }
                        if(row.fieldType === 'virtual') {
                            dt = 'VIRTUAL'
                        }
                        if(row.fieldType === 'double') {
                            dt = 'DOUBLE'
                        }
                        if(dt) {
                            let str = `${row.field}:{type: DataTypes.${dt},${an}${defaultValue}comment:'${row.title}'}, \n`
                            fieldStr = fieldStr + str
                        }
                    }
                }
            })
        }
        let tb = `// ${model.name}
const {DataTypes, db } = require("../db");
db.define('${par.modName}', {
${idstr}
${tenantStr}
${fieldStr}
${isDel}
${quick}
${cby}
${uby}
${dby}
${ctime}
${utime}
${dtime}
}, {
    tableName: '${par.tableName}',
    timestamps: false
});`
        saveFile(par.modName, tb)
    }
    catch (e) {
        console.log('模型文件保存失败')
    }
}
const exportOut = async (fname, data) => {
    const buffer = xlsx.build(data)
    let filename = fname + now() + '.xlsx'
    await fs.writeFileSync('./download/' + filename, buffer)
    return filename
}

const combFile = async (model) => {
    let ts = `timestamps: ${!!model.sysfield},`
    let fields = ``
    let softDel = ``
    if(model.paranoid) {
        softDel = `paranoid:${!!model.paranoid},`
        ts = `timestamps: true,`
    }
    if(model.columns) {
        model.columns.map(row =>{
            let len = ``
            let defaultValue = ``
            let unique = ``
            let comment = row.comment?`comment:'${row.comment}',`: `comment:'${row.title}',`
            let pk = ``
            if(row.length) {
                let lstr = `${row.length}`
                if(row.precision) {
                    lstr += `,${row.precision}`
                }
                len = `(${lstr})`
            }
            if(row.defaultValue) {
                defaultValue = `defaultValue:'${row.defaultValue}',`
            }
            if(row.dataType === 'UUID' && row.field==='id') {
                defaultValue = `defaultValue:fn('uuid_generate_v4'),`
            }
            // if((row.dataType === 'DATEONLY' || row.dataType === 'DATE') && !row.defaultValue) {
            // 	defaultValue = `defaultValue:fn('now'),`
            // }
            let autoincr = ''
            if(row.unique) {
                unique = `unique:'${row.unique}',`
            }
            if(row.primaryKey) {
                pk = `primaryKey:${!!row.primaryKey}, `
            }
            if(row.dataType === 'autoincr') {
                row.dataType = 'INTEGER'
                autoincr = ' autoIncrement: true,'
            }
            if(row.dataType === 'BOOLEAN') row.dataType = 'TINYINT'
            fields += `${row.field}: {type:DataTypes.${row.dataType}${len},${autoincr}allowNull:${!row.notNull},${defaultValue}${unique}${comment}${pk}  },\n`
        })
    }
    // 系统字段自动加人 创建人，最后更新人
    if(model.sysfield) {
        fields += `cby: {type:DataTypes.UUID,allowNull:true,comment:'创建人'  },\n`
        fields += `uby: {type:DataTypes.UUID,allowNull:true,comment:'更新人'  },\n`
    }
    // 如果是软删除，更新删除人
    if(model.paranoid) {
        fields += `dby: {type:DataTypes.UUID,allowNull:true,comment:'删除人'  },\n`
    }

    let str = `const {DataTypes, db,fn} = require("./db");
db.define('${model.tablename}', {
    ${fields}
}, {
    tableName: '${model.tablename}',${softDel}${ts}createdAt: 'ct', updatedAt: 'ut', deletedAt: 'dt',underscored: true,comment: '${model.title}'
});`
    return str
}

const getBtn = () => {
    return [
        {
            name: '新增', mobile: false,
            click: (inject, _this, _tool) => {
                _this.$jlayer.open({
                    formName: '客户管理-表单',
                    saved: () => {
                        inject.$f.exec('JGrid', 'doSearch')
                    }
                })
            }
        },
    ]
}
const btnClick = () => {
    return {
        toolbarClick: (inject, btn) => {

        }
    }
}

const openMobileSearch = () => {
    return {
        openMobileSearch: (inject) => {

        }
    }
}
const rowBtn = () => {
    return {
        "title": "操作",
        "width": 120,
        "fixed": "right",
        "slots": {
            "default": "op"
        },
        "btns": [{
            "name": "编辑",
            "click": (inject, row, _this, _tool) => {
                _this.$jlayer.open({
                    designName: '客户管理-表单',
                    initData: row,
                    width: 600,
                    height: 600,
                    saved: () => {
                        inject.$f.exec('JGrid', 'doSearch')
                    }
                })
            }},
            {
                "name": "删除",
                "confirm": "确定删除 ？",
                "show": "row.state==='正常'",
                "click": (inject, row, _this, _tool) => {
                    _tool.post('page/del', {
                        ids: [row.id], designName: '客户管理', type: 'del', beforeDel: {
                            designName: '客户管理',
                            func: 'beforeRowDel'
                        }
                    }).then(ret => {
                        inject.$f.exec('JGrid', 'doSearch')
                    })
                }},
            {
                "name": "恢复",
                "confirm": "确定恢复 ？",
                "show": "row.state==='删除'",
                "click": (inject, row, _this, _tool) => {
                    _tool.post('page/del', {
                        ids: [row.id], designName: '客户管理', type: 'unDel'
                    }).then(ret => {
                        inject.$f.exec('JGrid', 'doSearch')
                    })
                }}]}
}
const rowBtnClick = () => {
    return {
        rowBtnClick: (inject, {row, btn}) => {
            if (btn.name === '编辑') {
                _this.$jlayer.open({
                    formName: '我的客户-表单',
                    initData: row,
                    saved: () => {
                        inject.$f.exec('JGrid', 'doSearch')
                    }
                })
            }
            if (btn.name === '删除') {
                tools.post('page/del', {
                    ids: [row.id], modelName: '客户表',type: 'del'
                }).then(ret => {
                    inject.$f.exec('JGrid', 'doSearch')
                })
            }
            if (btn.name === '恢复') {
                tools.post('page/del', {
                    ids: [row.id], modelName: '客户表',type: 'unDel',
                }).then(ret => {
                    inject.$f.exec('JGrid', 'doSearch')
                })
            }
        }
    }
}

const saveFile =  (fileName, data) => {
    fs.writeFile('./models/tables/'+fileName+'.js', data, err => {
        if(err) {
        }
        else {
        }
    })
}
module.exports = router;
